package Chapter14;

import java.awt.print.Book;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * @author 杨森
 * @date 2022年10月25日 10:56
 */
public class CollectionIterator {
    public static void main(String[] args) {
        Collection col = new ArrayList();
        col.add(new Book1("三国演义", "罗贯中", 10.1));
        col.add(new Book1("小李飞刀", "古龙", 2.1));
        col.add(new Book1("红楼梦", "曹雪芹", 34.6));

//        System.out.println("col="+col);
//        遍历col集合
//        先得到col对应的迭代器
        Iterator it = col.iterator();
//        使用while循环遍历
        while (it.hasNext()) {//判断是否还有数据
            //返回下一个元素，类型是Object
            Object obj = it.next();
            System.out.println(obj);
        }

//        退出while循环后，这是iterator迭代器指向最后的元素
//        iterator.next()报错
//        如果希望在此遍历，需要重置我们的迭代器
        it = col.iterator();
        System.out.println("第二次遍历");
        while (it.hasNext()) {
            Object next =  it.next();
            System.out.println("第二次遍历："+next);
        }


    }
}

class Book1 {
    private String name;
    private String author;
    private double price;

    public Book1(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("Book{");
        sb.append("name='").append(name).append('\'');
        sb.append(", author='").append(author).append('\'');
        sb.append(", price=").append(price);
        sb.append('}');
        return sb.toString();
    }
}
